package com.tool.cn.use;

import java.io.BufferedReader;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 
 * @author wangzonghui
 * @date 2020年6月19日 上午11:03:53 
 * @Description:proto文件生成类
 * 		<dependency>
			<groupId>com.google.protobuf</groupId>
			<artifactId>protobuf-java</artifactId>
			<version>3.12.2</version>
		</dependency>
 */
public class ProtoUtil {
	
	public static void main(String[] args) {
		
		int maven=0; //是否为maven 0 是，1不是 
		String source;
		if(maven==0) {
			source=System.getProperty("user.dir")+"\\src\\main\\resources";
		}else {
			source=System.getProperty("user.dir")+"\\src";
		}
		
		File exeFile=new File(System.getProperty("user.dir")+"\\lib\\protoc.exe");
		String output=System.getProperty("user.dir")+"\\src\\main\\java\\";
		if(maven==0) {
			output=System.getProperty("user.dir")+"\\src\\main\\java\\";
		}else {
			output=System.getProperty("user.dir")+"\\src";
		}
		
		File[] fileList=getProto(source);
		createJava(fileList,exeFile,output);
		
	}
	
	/**
	 * 生成java文件
	 * protoc --java_out=. ./proto/InviteCode.proto
	 * @param fileList
	 */
	public static void createJava(File[] fileList,File exeFile,String output) {
		
		String cmdTmp=exeFile+" --java_out="+output+" -I ",cmd;
		Process ps;
		int exitcode;
		
		for(File file:fileList) {
			cmd=cmdTmp+file.getParent()+" "+file.getName();
			try {
				ps = Runtime.getRuntime().exec(cmd);
				exitcode=ps.waitFor();
				if (exitcode != 0) {
					 InputStream errorStream = ps.getErrorStream();
					 BufferedReader br = new BufferedReader(new InputStreamReader(errorStream));
					 String errContext="",line;
	                 while (true){
	                     line = br.readLine();
	                     if(line == null) break;
	                     errContext+=line;
	                 }
	                 br.close();
	                 
					System.err.println(cmd+" run is error code:"+ exitcode+" "+errContext);
				}else {
					System.out.println("Create Success"+file);
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
					
			
		}
	}
	
	/**
	 * 获取proto文件
	 * @param source
	 * @return
	 */
	public static File[] getProto(String source) {
		File[] fileList=new File(source).listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File paramFile, String paramString) {
				
				if(paramString.startsWith(".")||paramString.endsWith("~")||paramString.endsWith("tmp")){
					return false;
				}
				
				if(paramString.endsWith(".proto")) {
					return true;
				}
				return false;
			}
		});
		
		return fileList;
		
	}
}
